/*
 * @Date: 2022-09-16 09:09:44
 * @LastEditTime: 2022-09-16 09:24:01
 */
import router from './router'
import store from './store'
import { Message } from 'element-ui'
import NProgress from 'nprogress' // progress bar
import 'nprogress/nprogress.css' // progress bar style
// import { getToken } from '@/utils/auth' // get token from cookie
import getPageTitle from '@/utils/get-page-title'


NProgress.configure({ showSpinner: false })

const whiteList = ['/login']

router.beforeEach(async (to, from, next) => {
  NProgress.start()
  document.title = getPageTitle(to.meta.title)
  // const hasToken = getToken()
  // 从store中获取token, 根据是否拿到token跳转时做判断 
  const token = store.state.user.token;

  if (token) {
    if (to.path === '/login') {
      // 如果拿到token, 去往login页面, 放行去首页
      next({ path: '/' })
      NProgress.done()
    } else {
      const hasGetUserInfo = store.getters.name
      // console.log(hasGetUserInfo);
      if (hasGetUserInfo) {
        // 如果拿到了用户信息, 放行
        NProgress.done()
        next()
      } else {
        // 没拿到用户信息, 发请求获取用户信息
        try {
          await store.dispatch('user/getInfo')
          next(to)
        } catch (error) {
          // token过期的处理
          await store.dispatch('user/resetToken')
          Message.error(error || 'Has Error')
          next(`/login?redirect=${to.path}`)
          NProgress.done()
        }
      }
    }
  } else {
    // 没拿到token的处理
    if (whiteList.indexOf(to.path) !== -1) {
      next()
    } else {
      next(`/login?redirect=${to.path}`)
      NProgress.done()
    }
  }
})

router.afterEach(() => {
  NProgress.done()
})
